/**
 * 
 */
package com.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author jinmei.wang
 * 
 */
public class ConfigUtil {

	public final static String DBCP_NAME = "dbcp.name";

	private final static Map<String, Properties> sections;
	static {
		sections = new HashMap<String, Properties>();
		try {
			String section = ".";
			sections.put(section, new Properties());
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
					ConfigUtil.class.getResource("/cms.cfg").getFile()), "UTF-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				
				if (line.length() == 0 || line.startsWith("#"))
					continue;

				if (line.matches("\\[.*\\]")) {
					String sec = line.replaceFirst("\\[(.*)\\]", "$1").trim();
					if (!section.equals(sec)) {
						section = sec;
						sections.put(section, new Properties());
					}
				} else if (line.matches(".*=.*")) {
					int i = line.indexOf('=');
					String name = line.substring(0, i).trim();
					String value = line.substring(i + 1).trim();
					sections.get(section).setProperty(name, value);
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String get(String section, String key)
	{
		if (section == null || section.length() == 0)
		{
			section = ".";
		}
		
		if (sections.containsKey(section))
		{
			if (sections.get(section).containsKey(key))
			{
				return sections.get(section).getProperty(key);
			}
			else
			{
				if (!section.equals(".") && sections.get(".").containsKey(key))
				{
					return sections.get(".").getProperty(key);
				}
			}
		}
		return null;
	}
	
	public static String get(String key)
	{
		if (sections.containsKey("."))
			return sections.get(".").getProperty(key);
		return null;
	}
}
